package com.work.csms.controller;

import com.work.csms.dao.Money;
import com.work.csms.service.MoneyService;
import com.work.csms.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/money")
@CrossOrigin(originPatterns = "*",allowCredentials ="true")
public class MoneyController {

    @Autowired(required = false)
    private MoneyService moneyService;
    @Autowired(required = false)
    private UserService userService;

    @PostMapping("/list")
    public List<Money> list(@RequestBody Money money) throws Exception {
        return moneyService.list(money);
    }

    @RequestMapping("/getMoneyById")
    public Money getMoneyById(@RequestBody Money money) throws Exception {
        Integer id = money.getId();
        if(id == null) {
            return null;
        } else {
            return moneyService.getMoneyById(id);
        }
    }

    @RequestMapping("/saveOrUpdate")
    public Map<String, Object> saveOrUpdate(@RequestBody Money money) throws Exception {
        Map<String, Object> result = new HashMap<>();
        Integer id = money.getId();
        money.setDate(new Date());
        if (Objects.isNull(id)) {
            moneyService.save(money);
        } else {
            moneyService.update(money);
        }
        if (money.getMoney() != null) {
            userService.updateMoneyByUserid(money.getUserid(), money.getMoney());
        }
        result.put("success", true);
        return result;
    }

    @RequestMapping("/deleted")
    public Map<String, Object> deleted(@RequestBody Money money) throws Exception {
        Map<String, Object> result = new HashMap<>();
        Integer id = money.getId();
        if (Objects.isNull(id)) {
            result.put("msg", "钱款使用id不存在");
        } else {
            moneyService.deleted(money.getId());
            result.put("success", true);
        }
        return result;
    }
}
